package com.ruoyi.functiontest.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.RoadInterchangeTest;
import com.ruoyi.functiontest.service.IRoadInterchangeTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 枢纽互通里程实测数据测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-25
 */
@RestController
@RequestMapping("/functiontest/RoadInterchangeTest")
public class RoadInterchangeTestController extends BaseController
{
    @Autowired
    private IRoadInterchangeTestService roadInterchangeTestService;

    /**
     * 查询枢纽互通里程实测数据测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:list')")
    @GetMapping("/list")
    public AjaxResult list(RoadInterchangeTest roadInterchangeTest)
    {
        List<RoadInterchangeTest> list = roadInterchangeTestService.selectRoadInterchangeTestList(roadInterchangeTest);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = roadInterchangeTest.getRoadName() != null && !roadInterchangeTest.getRoadName().isEmpty() ||
                                   roadInterchangeTest.getInterchangeName() != null && !roadInterchangeTest.getInterchangeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<RoadInterchangeTest> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出枢纽互通里程实测数据测试列表
     * 简化导出逻辑：直接导出数据库原始存储格式，无需树形结构处理
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:export')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RoadInterchangeTest roadInterchangeTest)
    {
        // 简化导出逻辑：直接导出数据库原始存储格式，无需树形结构处理
        List<RoadInterchangeTest> list = roadInterchangeTestService.selectRoadInterchangeTestList(roadInterchangeTest);
        
        ExcelUtil<RoadInterchangeTest> util = new ExcelUtil<RoadInterchangeTest>(RoadInterchangeTest.class);
        util.exportExcel(response, list, "枢纽互通里程实测数据测试数据");
    }

    /**
     * 获取枢纽互通里程实测数据测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(roadInterchangeTestService.selectRoadInterchangeTestById(id));
    }

    /**
     * 新增枢纽互通里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:add')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RoadInterchangeTest roadInterchangeTest)
    {
        return toAjax(roadInterchangeTestService.insertRoadInterchangeTest(roadInterchangeTest));
    }

    /**
     * 修改枢纽互通里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:edit')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RoadInterchangeTest roadInterchangeTest)
    {
        return toAjax(roadInterchangeTestService.updateRoadInterchangeTest(roadInterchangeTest));
    }

    /**
     * 删除枢纽互通里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:remove')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否可以删除节点（父节点必须在子节点删除完后才能删除）
        for (Long id : ids) {
            if (roadInterchangeTestService.hasChildById(id)) {
                return error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        
        return toAjax(roadInterchangeTestService.deleteRoadInterchangeTestByIds(ids));
    }
    
    /**
     * 构建树形结构
     */
    private List<RoadInterchangeTest> buildTree(List<RoadInterchangeTest> list) {
        // 构建父子关系映射
        Map<Long, RoadInterchangeTest> nodeMap = new HashMap<>();
        List<RoadInterchangeTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (RoadInterchangeTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (RoadInterchangeTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                RoadInterchangeTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<RoadInterchangeTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<RoadInterchangeTest> children = (List<RoadInterchangeTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }
    
    /**
     * 将树形结构按层次顺序展平为列表
     */
    private void flattenTree(List<RoadInterchangeTest> treeList, List<RoadInterchangeTest> result) {
        for (RoadInterchangeTest node : treeList) {
            // 添加当前节点到结果列表
            result.add(node);
            
            // 递归处理子节点
            if (node.getChildren() != null) {
                @SuppressWarnings("unchecked")
                List<RoadInterchangeTest> children = (List<RoadInterchangeTest>) node.getChildren();
                flattenTree(children, result);
            }
        }
    }
    
    /**
     * 导入枢纽互通里程实测数据测试数据
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:import')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<RoadInterchangeTest> util = new ExcelUtil<RoadInterchangeTest>(RoadInterchangeTest.class);
        List<RoadInterchangeTest> importList = util.importExcel(file.getInputStream());
        
        // 简化导入逻辑：直接按照Excel原始格式导入，通过id和parentid来确定数据
        String message = roadInterchangeTestService.importRoadInterchangeTest(importList, updateSupport);
        return success(message);
    }

    /**
     * 导入模板下载
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        List<RoadInterchangeTest> list = new ArrayList<>();
        
        // 添加示例数据 - 六安路段
        RoadInterchangeTest data1 = new RoadInterchangeTest();
        data1.setId(2L);
        data1.setParentId(0L);
        data1.setRoadName("六安");
        data1.setInterchangeName("");
        data1.setDirection1("");
        data1.setDirection2("");
        data1.setRampType("");
        data1.setRampLength(null);
        data1.setRemark("");
        list.add(data1);
        
        RoadInterchangeTest data2 = new RoadInterchangeTest();
        data2.setId(3L);
        data2.setParentId(2L);
        data2.setRoadName("");
        data2.setInterchangeName("同云枢纽互通");
        data2.setDirection1("");
        data2.setDirection2("");
        data2.setRampType("");
        data2.setRampLength(null);
        data2.setRemark("");
        list.add(data2);
        
        RoadInterchangeTest data3 = new RoadInterchangeTest();
        data3.setId(4L);
        data3.setParentId(3L);
        data3.setRoadName("");
        data3.setInterchangeName("");
        data3.setDirection1("P4");
        data3.setDirection2("P5");
        data3.setRampType("主线平均长度");
        data3.setRampLength(new BigDecimal("158.215"));
        data3.setRemark("");
        list.add(data3);
        
        RoadInterchangeTest data4 = new RoadInterchangeTest();
        data4.setId(6L);
        data4.setParentId(3L);
        data4.setRoadName("");
        data4.setInterchangeName("");
        data4.setDirection1("P6");
        data4.setDirection2("P7");
        data4.setRampType("主线平均长度");
        data4.setRampLength(new BigDecimal("213.440"));
        data4.setRemark("");
        list.add(data4);
        
        RoadInterchangeTest data5 = new RoadInterchangeTest();
        data5.setId(7L);
        data5.setParentId(3L);
        data5.setRoadName("");
        data5.setInterchangeName("");
        data5.setDirection1("P5");
        data5.setDirection2("P6");
        data5.setRampType("主线平均长度");
        data5.setRampLength(new BigDecimal("279.175"));
        data5.setRemark("");
        list.add(data5);
        
        RoadInterchangeTest data6 = new RoadInterchangeTest();
        data6.setId(8L);
        data6.setParentId(3L);
        data6.setRoadName("");
        data6.setInterchangeName("");
        data6.setDirection1("P7");
        data6.setDirection2("P8");
        data6.setRampType("主线平均长度");
        data6.setRampLength(new BigDecimal("160.825"));
        data6.setRemark("");
        list.add(data6);
        
        RoadInterchangeTest data7 = new RoadInterchangeTest();
        data7.setId(9L);
        data7.setParentId(3L);
        data7.setRoadName("");
        data7.setInterchangeName("");
        data7.setDirection1("P8");
        data7.setDirection2("P9");
        data7.setRampType("主线平均长度");
        data7.setRampLength(new BigDecimal("608.865"));
        data7.setRemark("");
        list.add(data7);
        
        RoadInterchangeTest data8 = new RoadInterchangeTest();
        data8.setId(10L);
        data8.setParentId(3L);
        data8.setRoadName("");
        data8.setInterchangeName("");
        data8.setDirection1("P9");
        data8.setDirection2("P10");
        data8.setRampType("主线平均长度");
        data8.setRampLength(new BigDecimal("933.720"));
        data8.setRemark("");
        list.add(data8);
        
        RoadInterchangeTest data9 = new RoadInterchangeTest();
        data9.setId(11L);
        data9.setParentId(3L);
        data9.setRoadName("");
        data9.setInterchangeName("");
        data9.setDirection1("P9");
        data9.setDirection2("P3");
        data9.setRampType("A匝道");
        data9.setRampLength(new BigDecimal("929.060"));
        data9.setRemark("");
        list.add(data9);
        
        RoadInterchangeTest data10 = new RoadInterchangeTest();
        data10.setId(12L);
        data10.setParentId(3L);
        data10.setRoadName("");
        data10.setInterchangeName("");
        data10.setDirection1("P3");
        data10.setDirection2("P7");
        data10.setRampType("B匝道");
        data10.setRampLength(new BigDecimal("761.010"));
        data10.setRemark("");
        list.add(data10);
        
        RoadInterchangeTest data11 = new RoadInterchangeTest();
        data11.setId(13L);
        data11.setParentId(3L);
        data11.setRoadName("");
        data11.setInterchangeName("");
        data11.setDirection1("P3");
        data11.setDirection2("P8");
        data11.setRampType("C匝道");
        data11.setRampLength(new BigDecimal("944.710"));
        data11.setRemark("");
        list.add(data11);
        
        RoadInterchangeTest data12 = new RoadInterchangeTest();
        data12.setId(14L);
        data12.setParentId(3L);
        data12.setRoadName("");
        data12.setInterchangeName("");
        data12.setDirection1("P6");
        data12.setDirection2("P3");
        data12.setRampType("D匝道");
        data12.setRampLength(new BigDecimal("1125.170"));
        data12.setRemark("");
        list.add(data12);
        
        RoadInterchangeTest data13 = new RoadInterchangeTest();
        data13.setId(15L);
        data13.setParentId(3L);
        data13.setRoadName("");
        data13.setInterchangeName("");
        data13.setDirection1("P1");
        data13.setDirection2("P3");
        data13.setRampType("E匝道");
        data13.setRampLength(new BigDecimal("1823.730"));
        data13.setRemark("");
        list.add(data13);
        
        RoadInterchangeTest data14 = new RoadInterchangeTest();
        data14.setId(16L);
        data14.setParentId(3L);
        data14.setRoadName("");
        data14.setInterchangeName("");
        data14.setDirection1("P4");
        data14.setDirection2("P1");
        data14.setRampType("F匝道");
        data14.setRampLength(new BigDecimal("943.000"));
        data14.setRemark("");
        list.add(data14);
        
        RoadInterchangeTest data15 = new RoadInterchangeTest();
        data15.setId(17L);
        data15.setParentId(3L);
        data15.setRoadName("");
        data15.setInterchangeName("");
        data15.setDirection1("P1");
        data15.setDirection2("P5");
        data15.setRampType("G匝道");
        data15.setRampLength(new BigDecimal("577.590"));
        data15.setRemark("");
        list.add(data15);
        
        RoadInterchangeTest data16 = new RoadInterchangeTest();
        data16.setId(19L);
        data16.setParentId(2L);
        data16.setRoadName("");
        data16.setInterchangeName("木咱枢纽互通");
        data16.setDirection1("");
        data16.setDirection2("");
        data16.setRampType("");
        data16.setRampLength(null);
        data16.setRemark("");
        list.add(data16);
        
        RoadInterchangeTest data17 = new RoadInterchangeTest();
        data17.setId(20L);
        data17.setParentId(19L);
        data17.setRoadName("");
        data17.setInterchangeName("");
        data17.setDirection1("P2-P3");
        data17.setDirection2("P3-P2");
        data17.setRampType("主线平均长度");
        data17.setRampLength(new BigDecimal("934.230"));
        data17.setRemark("");
        list.add(data17);
        
        RoadInterchangeTest data18 = new RoadInterchangeTest();
        data18.setId(21L);
        data18.setParentId(3L);
        data18.setRoadName("");
        data18.setInterchangeName("");
        data18.setDirection1("P1");
        data18.setDirection2("P10");
        data18.setRampType("H匝道");
        data18.setRampLength(new BigDecimal("2435.140"));
        data18.setRemark("");
        list.add(data18);
        
        RoadInterchangeTest data19 = new RoadInterchangeTest();
        data19.setId(22L);
        data19.setParentId(3L);
        data19.setRoadName("");
        data19.setInterchangeName("");
        data19.setDirection1("P9");
        data19.setDirection2("P1");
        data19.setRampType("I匝道");
        data19.setRampLength(new BigDecimal("1431.690"));
        data19.setRemark("");
        list.add(data19);
        
        RoadInterchangeTest data20 = new RoadInterchangeTest();
        data20.setId(23L);
        data20.setParentId(3L);
        data20.setRoadName("");
        data20.setInterchangeName("");
        data20.setDirection1("P3");
        data20.setDirection2("P1");
        data20.setRampType("J匝道");
        data20.setRampLength(new BigDecimal("1309.030"));
        data20.setRemark("");
        list.add(data20);
        
        RoadInterchangeTest data21 = new RoadInterchangeTest();
        data21.setId(24L);
        data21.setParentId(19L);
        data21.setRoadName("");
        data21.setInterchangeName("");
        data21.setDirection1("P1");
        data21.setDirection2("P3");
        data21.setRampType("A匝道");
        data21.setRampLength(new BigDecimal("873.710"));
        data21.setRemark("");
        list.add(data21);
        
        RoadInterchangeTest data22 = new RoadInterchangeTest();
        data22.setId(25L);
        data22.setParentId(19L);
        data22.setRoadName("");
        data22.setInterchangeName("");
        data22.setDirection1("P2");
        data22.setDirection2("P1");
        data22.setRampType("B匝道");
        data22.setRampLength(new BigDecimal("932.620"));
        data22.setRemark("");
        list.add(data22);
        
        RoadInterchangeTest data23 = new RoadInterchangeTest();
        data23.setId(26L);
        data23.setParentId(19L);
        data23.setRoadName("");
        data23.setInterchangeName("");
        data23.setDirection1("P3");
        data23.setDirection2("P1");
        data23.setRampType("C匝道");
        data23.setRampLength(new BigDecimal("1180.770"));
        data23.setRemark("");
        list.add(data23);
        
        ExcelUtil<RoadInterchangeTest> util = new ExcelUtil<RoadInterchangeTest>(RoadInterchangeTest.class);
        util.exportExcel(response, list, "枢纽互通里程实测数据测试导入模板");
    }
    
    /**
     * 实测单位批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:fieldAudit')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.UPDATE)
    @PostMapping("/fieldAudit/batch")
    public AjaxResult fieldAuditBatch()
    {
        try {
            // 批量更新所有记录的review1字段为0
            int updatedCount = roadInterchangeTestService.updateReview1ToZero();
            System.out.println("实测单位批量审核完成，更新记录数：" + updatedCount);
            return success("实测单位批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("实测单位批量审核失败：" + e.getMessage());
            return error("实测单位批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 业主批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:ownerAudit')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.UPDATE)
    @PostMapping("/ownerAudit/batch")
    public AjaxResult ownerAuditBatch(@RequestBody Map<String, Object> params)
    {
        try {
            Long deptId = params.get("deptId") != null ? Long.valueOf(params.get("deptId").toString()) : null;
            Long roleId = params.get("roleId") != null ? Long.valueOf(params.get("roleId").toString()) : null;
            
            System.out.println("业主批量审核 - 审核所有数据，deptId: " + deptId + ", roleId: " + roleId);
            
            // 1. 校验所有数据的review1字段是否都为0
            boolean allReview1Zero = roadInterchangeTestService.checkAllReview1IsZero();
            if (!allReview1Zero) {
                return error("业主批量审核失败：存在未通过实测单位审核的数据，请先完成实测单位审核");
            }
            
            // 2. 构建查询条件
            RoadInterchangeTest queryCondition = new RoadInterchangeTest();
            queryCondition.setDeptId(deptId);
            queryCondition.setRoleId(roleId);
            
            // 3. 从params中提取查询条件
            if (params.get("roadName") != null) {
                queryCondition.setRoadName(params.get("roadName").toString());
            }
            if (params.get("interchangeName") != null) {
                queryCondition.setInterchangeName(params.get("interchangeName").toString());
            }
            
            // 4. 根据条件批量更新业主审核状态
            int updatedCount = roadInterchangeTestService.updateReview2ToZeroByCondition(queryCondition);
            
            System.out.println("业主批量审核完成，更新记录数：" + updatedCount);
            return success("业主批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("业主批量审核失败：" + e.getMessage());
            return error("业主批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 中心批量审核
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:centerAudit')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.UPDATE)
    @PostMapping("/centerAudit/batch")
    public AjaxResult centerAuditBatch()
    {
        try {
            System.out.println("中心批量审核 - 审核所有数据");
            
            // 1. 校验所有数据的review1和review2字段是否都不为空且都为0
            boolean allReview1AndReview2Zero = roadInterchangeTestService.checkAllReview1AndReview2AreZero();
            if (!allReview1AndReview2Zero) {
                return error("中心批量审核失败：存在未通过实测单位审核或业主审核的数据，请先完成前序审核");
            }
            
            // 2. 批量更新中心审核状态
            int updatedCount = roadInterchangeTestService.updateReview3ToZero();
            
            System.out.println("中心批量审核完成，更新记录数：" + updatedCount);
            return success("中心批量审核成功，共更新" + updatedCount + "条记录");
        } catch (Exception e) {
            System.err.println("中心批量审核失败：" + e.getMessage());
            return error("中心批量审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 同步数据到正式表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:sync')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.OTHER)
    @PostMapping("/sync")
    public AjaxResult syncDataToRoadInterchange()
    {
        try {
            System.out.println("开始同步数据到正式表");
            
            // 1. 校验所有数据的review1、review2和review3字段是否都不为空且都为0
            boolean allReviewZero = roadInterchangeTestService.checkAllReviewFieldsAreZero();
            if (!allReviewZero) {
                return error("同步失败：存在未通过审核的数据");
            }
            
            // 2. 执行数据同步
            String syncResult = roadInterchangeTestService.syncDataToRoadInterchange();
            
            System.out.println("数据同步完成：" + syncResult);
            return success(syncResult);
        } catch (Exception e) {
            System.err.println("数据同步失败：" + e.getMessage());
            return error("同步失败：" + e.getMessage());
        }
    }
}
